//
//  AddView.swift
//  TodoList
//
//  Created by 刘圣洁 on 2025/6/12.
//

import SwiftUI

struct AddView: View {
    
    @Environment(\.dismiss) var dismiss
    @EnvironmentObject var listViewModel: ListViewModel
    @State var textfieldtext: String = ""
    
    @State var showAlert: Bool = false
    var body: some View {
        ScrollView {
            
            VStack(spacing: 20) {
                TextField("输入内容", text: $textfieldtext)
                    .foregroundStyle(Color.accentColor)
                    .padding(.horizontal)
                    .frame(height: 55)
                    .background(Color(UIColor.secondarySystemBackground))
                .cornerRadius(10)
                
                Button {
                    saveButtonPressed()
                } label: {
                    Text("保存")
                        .foregroundStyle(.white)
                        .font(.headline)
                        .frame(height: 55)
                        .frame(maxWidth: .infinity)
                        .background(Color.accentColor)
                        .clipShape(RoundedRectangle(cornerRadius: 10))
                }

            }
            .padding(14)
        }
        .navigationTitle("新增 🖊️")
        .alert("您的新事项内容必须大于3个字！！！😨", isPresented: $showAlert) {
            Button("确定",role: .cancel) {}
        }
    }
    
    func saveButtonPressed() {
        if textIsAppropriate() {
            listViewModel.addItem(title: textfieldtext)
            dismiss()
        }else{
            
            //添加震动效果
            HapticsManager.instance.notification(type: .warning)
            showAlert.toggle()
        }
    }
    
    func textIsAppropriate() -> Bool {
        return textfieldtext.count >= 3
    }
    
}

#Preview {
    NavigationStack {
        AddView()
    }.environmentObject(ListViewModel())
}
